import React, { Component } from 'react'
import Input from './Input'
import Dialog from './Dialog'
import apis from '../apis'
import styles from './result.module.css'
import { Toast } from 'antd-mobile'

const ScoreViewer = ({ children, style, center, bold, color = '#3aceb8', size = '10vw', desc = 'Score' }) => {
    return (
        <div className={styles['score-view']} style={ style }>
            <div className={styles['desc']}>{desc}</div>
            <div className={styles['score']} style={{ color, fontSize: size, ...bold && { fontWeight: 'bolder' }, ...center && { textAlign: 'center', textAlign: 'justify' }}}>{children}</div>
        </div>
    )
}

class Result extends Component {
    constructor(props) {
        super(props)
        if(props.location.state && props.location.state.token) {
            this.token = props.location.state.token
        } else {
            this.props.history.push('/')
        }
        
        this.state = {
            hasCaptcha: false,
            captcha: '',
            captchaImg: '',
            exam: {
                name: '',
                ID: '000000000000000',
                type: 0,
            },
            score: {
                score: '',
                oral: '',
                listening: '',
                reading: '',
                writing: '',
            },
            sharing: false,
        }
    }

    componentDidMount() {
        Toast.loading('加载中...', 0)
        apis.exam(this.token).then(data => {
            this.setState({
                exam: {
                    name: data.name,
                    ID: data.ID,
                    type: data.ID[9] == 1 ? 4 : 6,
                },
                score: {
                    score: data.score,
                    oral: data.oralLevel,
                    listening: data.listening,
                    reading: data.reading,
                    writing: data.writing,
                },
                hasCaptcha: data.score ? false : true,
            })
            if(data.score) {
                Toast.hide()
            }
        }).catch(err => {
            Toast.hide()
            if(err.response.status == 401) {
                this.props.history.push('/')
                return
            }
            Toast.fail(err.msg, 2, null, false)
        })
    }

    captchaFinish() {
        Toast.hide()
    }

    refreshCaptcha(state) {
        apis.neeacet(this.token, state.exam.ID).then(data => {
            this.setState({ captchaImg: data.img })
        }).catch(err => {
            Toast.hide()
            Toast.fail(err.msg, 2, null, false)
        })
    }

    componentWillUpdate(nextProps, nextState) {
        if(!this.state.hasCaptcha && nextState.hasCaptcha) {
            this.refreshCaptcha(nextState)
        }
    }

    computedType() {
        switch(this.state.exam.type) {
            default:
                return '未知'
            case 4:
                return '四级 CET-4'
            case 6:
                return '六级 CET-6'
        }
    }

    computedNumber() {
        const number = this.state.exam.ID
        return [number.slice(0, 6), number.slice(6, 10), number.slice(10, 15)].join(' ')
    }

    formatScore(score) {
        let ret = parseFloat(score).toFixed(1)
        return isNaN(ret) ? '0.0' : ret
    }

    submitCaptcha() {
        Toast.loading('加载中...', 0)
        apis.neeacetSubmit(this.token, this.state.exam.ID, this.state.captcha).then(data => {
            this.setState({
                score: {
                    score: data.score,
                    oral: data.oralLevel,
                    listening: data.listening,
                    reading: data.reading,
                    writing: data.writing,
                },
                hasCaptcha: false,
            })
            Toast.hide()
        }).catch(err => {
            this.refreshCaptcha(this.state)
            Toast.hide()
            Toast.fail(err.msg, 2, null, false)
        })
    }

    toggleShare() {
        if(this.state.sharing) {
            this.setState({ sharing: false })
        } else {
            this.setState({ sharing: true })
        }
    }

    handleChange(event) {
        const target = event.target
        this.state[target.name] !== undefined && this.setState({
            [target.name]: target.value
        })
    }

    render() {
        return (
            <div className={styles['page-result']}>
                <div className={styles['container']}>
                    <div className={styles['heading']}>
                        <img src={require('../resources/result-info.svg')} alt="考试信息" />
                    </div>
                    <div className={styles['flexbox']}>
                        <ScoreViewer desc="姓名" size="5.6vw" bold style={{ flexGrow: 1 }}>{this.state.exam.name}</ScoreViewer>
                        <ScoreViewer desc="报考类型" bold size="5.6vw">{this.computedType()}</ScoreViewer>
                    </div>
                    <ScoreViewer desc="准考证号" size="9vw" center>{this.computedNumber()}</ScoreViewer>
                    <div className={styles['heading']}>
                        <img src={require('../resources/result-score.svg')} alt="考试成绩" />
                    </div>
                    <div className={styles['score-box']}>
                        {this.state.hasCaptcha && <div className={styles['mask']}>
                            <div className={styles['flexbox']}>
                                <Input name="captcha"
                                    ref="captchaInput"
                                    style={{ fontFamily: "'DIN Alternate', sans-serif" }}
                                    onChange={this.handleChange.bind(this)}
                                    placeholder="输入右侧的字符" />
                                <img className={styles['captcha']} src={this.state.captchaImg} alt="验证码" onClick={this.refreshCaptcha.bind(this, this.state)} onLoad={this.captchaFinish.bind(this)} />
                            </div>
                            <button className={styles['btn-query']} 
                                disabled={this.state.captcha.length < 4} 
                                onClick={this.submitCaptcha.bind(this)}>查询成绩</button>
                        </div>}
                        <div className={styles['flexbox']}>
                            <ScoreViewer desc="总分" color="#52d1ef" style={{ flexGrow: 1 }}>{this.formatScore(this.state.score.score)}</ScoreViewer>
                            <ScoreViewer desc="口语成绩" style={{ width: '23vw' }} color="#fcc05e">{this.state.score.oral}</ScoreViewer>
                        </div>
                        <div className={styles['flexbox']}>
                            <ScoreViewer desc="听力" style={{ flexGrow: 1 }} color="#52d1ef">{this.formatScore(this.state.score.listening)}</ScoreViewer>
                            <ScoreViewer desc="阅读" style={{ flexGrow: 1 }} color="#52d1ef">{this.formatScore(this.state.score.reading)}</ScoreViewer>
                            <ScoreViewer desc="写作" style={{ width: '23vw' }} color="#52d1ef">{this.formatScore(this.state.score.writing)}</ScoreViewer>
                        </div>
                    </div>
                    <button onClick={this.toggleShare.bind(this)} className={styles['btn']}>
                        <img src={require('../resources/result-share.svg')} alt="分享页面" />
                    </button>
                    <div className={styles['copyright']}>
                    前端：<strong>欧阳亚坤</strong> / 后端：<strong>罗经宇</strong> / 运营：<strong>卢娇</strong><br/>
                    <span style={{ color: '#3aceb8', fontWeight: 'bold' }}>家园工作室出品</span>
                    </div>
                </div>
                <div className={styles['share-mask']} style={{ display: this.state.sharing ? 'block' : 'none' }} onClick={this.toggleShare.bind(this)}>
                    <div className={styles['result-share']}></div>
                </div>
            </div>
        )
    }
}

export default Result